package com.axend.aerosense.pay.viewmodel;

import android.app.Activity;
import android.app.Dialog;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.pay.GooglePayClient;
import com.axend.aerosense.pay.PayCallback;
import com.axend.aerosense.pay.R;
import com.axend.aerosense.pay.SkuType;
import com.axend.aerosense.pay.entity.GetVipInfoBean;
import com.axend.aerosense.pay.entity.PayModeBean;
import com.axend.aerosense.pay.entity.VerifyOrderBean;
import com.axend.aerosense.pay.entity.VipCenterContentBean;
import com.axend.aerosense.pay.entity.VipMoneyCardBean;
import com.axend.aerosense.pay.widget.PayTipsDialog;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.disposables.Disposable;

/**
 * @author ChenHongWei
 * @date :2020/12/18 15:11
 */

public class VipHomeViewModel extends CustomBaseViewModel<VipCenterContentBean> {

    public MutableLiveData<Boolean> autoRenew = new MutableLiveData<>(false);//自动续费
    public MutableLiveData<Boolean> isVip = new MutableLiveData<>(false);//是否是会员
    public MutableLiveData<String> dataTime = new MutableLiveData<>();//日期

    public static final int ZFB_PAY_AUTO_REQUEST_CODE_ID = 1002;  //requestCode
    private Disposable disposable = null;
    private PayTipsDialog payTipsDialog;
    private IOperationResult operationResult;
    private Activity mActivity;
    private Dialog progressDialog;
    private GooglePayClient payClient;
    private PayTipsDialog verifyOrderDialog;
    private int retryCount = 0;
    private int maxRetry = 3;

    public VipHomeViewModel(IBaseView baseViewImpl, ILoadDataResult<VipCenterContentBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
    }

    // 加载VIP 界面内容
    @Override
    public void onLoad() {
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }

        //初次请求数据，是否是会员，会员时间
        disposable = EasyHttp.post(UrlApi.URL.QueryAllUserInfoResult.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new GetVipInfoBean()))
                .execute(new SimpleCallBack<VipCenterContentBean>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(VipCenterContentBean vipCenterBean) {
                        loadDataSuccess(vipCenterBean);
                    }

                    @Override
                    public void onTokenExpire() {
                        //登录界面不做处理
                        ToastUtils.showShort(com.axend.aerosense.dev.R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }
                });

    }

    //点击支付方法
    public synchronized void vipPay(Activity activity, VipMoneyCardBean vipMoneyCardBean, PayModeBean payModeBean, IOperationResult operationResult) {
        this.operationResult = operationResult;
        this.mActivity = activity;

        progressDialog = LoadingDialog.getProgressDialog(activity).getDialog();
        progressDialog.show();

        payTipsDialog = new PayTipsDialog(activity, null);
        payTipsDialog.setOnClickBottomListener(() -> payTipsDialog.dismiss());

        //谷歌支付
        if (payModeBean.getPayType() == PayModeBean.GOOGLE_PAY && VipMoneyCardBean.checkVipType(vipMoneyCardBean.getVipType())){
            SkuType skuType;
            if (!VipMoneyCardBean.isSubscribe(vipMoneyCardBean.getVipType())){
                skuType = SkuType.INAPP;
            }else {
                skuType = SkuType.SUBS;
            }

            String productId = vipMoneyCardBean.getGoodsIdentifiers();
            if (TextUtils.isEmpty(productId)){
                operationResult.onFail();
                progressDialog.dismiss();
                return;
            }

            //验证通过，进行支付
            googlePay(skuType, productId);
        }else {
            operationResult.onFail();
            progressDialog.dismiss();
        }
    }

    /**
     * 进行谷歌支付
     * @param skuType  套餐类型：单独购买商品/续订商品
     * @param purchaseId  商品ID
     */
    private synchronized void googlePay(SkuType skuType, String purchaseId){
        payClient = GooglePayClient.Builder()
                .setSkuType(skuType)
                .setPurchaseId(purchaseId)
                .setActivity(mActivity)
                .setPayCallback(new PayCallback() {
                    @Override
                    public void paySuccess(boolean isHistoryGoods, String purchaseJson) {
                        LogUtils.d("purchaseJson:" + purchaseJson);
                        verifyOrder(isHistoryGoods, purchaseJson);
                    }

                    @Override
                    public void payError(int state) {
                        LogUtils.d("支付错误：" + state);
                        LogUtils.d(Thread.currentThread().getName());
                        mActivity.runOnUiThread(()->{
                            //支付失败
                            progressDialog.dismiss();
                            if (state == GooglePayClient.STATE_USER_CANCELED) {
                                //用户取消
                                ToastUtils.showShort(R.string.pay_vip_cancel);
                            } else if (state == GooglePayClient.STATE_NETWORK_ERROR || state == GooglePayClient.STATE_UNKNOWN_ERROR) {
                                //网络错误或未知错误
                                ToastUtils.showShort(R.string.pay_unknown_error);
                            }else if (state == GooglePayClient.STATE_REPEAT_SUBSCRIBE){
                                //重复订阅
                                ToastUtils.showShort(R.string.pay_repeat_subscribe_tips);
                                LogUtils.d("用户已续订一个项目，不可重复续订！");
                            }else if (state == GooglePayClient.STATE_HISTORY_GOODS_ERROR){
                                LogUtils.d("处理历史订单错误！");
                            }
                        });
                    }
                })
                .build();
        payClient.queryPurchaseAndPay();
    }

    /**
     * 服务器验证订单
     * 历史订单只验证一次，当前订单验证3次
     * @param purchaseJson
     */
    private void verifyOrder(boolean isHistoryGoods, String purchaseJson){
        EasyHttp.post(UrlApi.URL.GooglePayVerifyOrder.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN))
                .upJson(JsonUtil.toJson(new VerifyOrderBean(purchaseJson)))
                .execute(new SimpleCallBack<BaseStringBean>() {
                    @Override
                    public void onTokenExpire() {
                        progressDialog.dismiss();
                        ToastUtils.showShort(com.axend.aerosense.dev.R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        operationResult.onFail();
                        progressDialog.dismiss();
                        if (!isHistoryGoods){
                            if (retryCount < maxRetry){
                                //递归
                                retryCount++;
                                verifyOrder(false, purchaseJson);
                            }else {
                                showVerifyOrderFailTips();
                            }
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean baseStringBean) {
                        retryCount = 0;
                        if (!isHistoryGoods) {
                            //当前订单

                            //更新用户会员状态
                            UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
                            userInfo.userVipState = 1;
                            MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.USR_INFO, userInfo);

                            operationResult.onSuccess();
                            progressDialog.dismiss();
                            payTipsDialog.show();
                        } else {
                            //上次未消费的订单

                        }
                    }
                });
    }

    /**
     * 显示订单验证失败提示
     */
    private void  showVerifyOrderFailTips(){
        verifyOrderDialog = new PayTipsDialog(mActivity, mActivity.getString(R.string.pay_order_verification_fail_tips));
        verifyOrderDialog.setOnClickBottomListener(() -> verifyOrderDialog.dismiss());
        verifyOrderDialog.show();
    }

    /**
     * 客户端支付成功后,发起的支付动作完成通知接口,服务端放回支付结果
     */
    /*public synchronized void noticeCheckPayResult(Activity activity, String orderId, int payStatus, IOperationResult operationResult, boolean checkOrder) {
        if(checkOrder || payStatus == PayCompleteBean.PAY_SUCCESS){

            payTipsDialog.setOnClickBottomListener(new PayTipsDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    noticeCheckPayResult(activity, orderId, payStatus, operationResult);
                    try{
                        payTipsDialog.dismiss();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            payTipsDialog.show();
            return;
        }
        noticeCheckPayResult(activity, orderId, payStatus, operationResult);
    }*/

    /*private synchronized  void noticeCheckPayResult(Activity activity, String orderId, int payStatus, IOperationResult operationResult){
        if(TextUtils.isEmpty(orderId)){
            return;
        }
        EasyHttp.post(UrlApi.URL.PayResultCheck.getUrl())//cancel   query
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN))
                .upJson(JsonUtil.toJson(new PayCompleteBean(orderId, payStatus)))
                .execute(new ProgressDialogCallBack<TipsBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(TipsBean tipsBean) {
                        dismissProgress();
                        ToastUtils.showShort(R.string.pay_vip_success);
//                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.VIP_CHANGE ,Integer.class).postValue(1);
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }

                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                        ToastUtils.showShort(com.axend.aerosense.dev.R.string.common_login_first);
                        //登录界面不做处理
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", false).greenChannel().navigation();
                        try{
                            activity.finish();
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
    }*/

    //与viewModel一起销毁
    @Override
    protected void onCleared() {
        if (null != disposable && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
        if (null != progressDialog){
            progressDialog.dismiss();
            progressDialog = null;
        }
        if (null != verifyOrderDialog){
            verifyOrderDialog.dismiss();
            verifyOrderDialog = null;
        }
        retryCount = 0;
        super.onCleared();
    }

}
